//
//  UIImageView+PreviewImage.m
//  CreditGroup
//
//  Created by 赵国腾 on 15/11/18.
//  Copyright © 2015年 JPlay. All rights reserved.
//

#import "UIImageView+PreviewImage.h"

@implementation UIImageView (PreviewImage)

// 给图片添加放大预览功能
- (void)showPreviewImage {
    
    self.userInteractionEnabled = YES;
    
    // 给头像添加手势
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self
                                                                                action:@selector(showBiggerHeaderImage:)];
    [self addGestureRecognizer:tapGesture];
}

// 放大头像
- (void)showBiggerHeaderImage:(UITapGestureRecognizer *)gesture {
    
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    
    UIView *bgView = [[UIView alloc] initWithFrame:keyWindow.bounds];
    bgView.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
    [keyWindow addSubview:bgView];
    
    CGRect smallImgViewFrame = [self.superview convertRect:self.frame toView:keyWindow];
    
    UIImageView *imgView = [[UIImageView alloc]initWithFrame:smallImgViewFrame];
    imgView.contentMode = UIViewContentModeScaleAspectFit;
    imgView.image = self.image;
    [bgView addSubview:imgView];
    
    [UIView animateWithDuration:0.3 animations:^{
        
        imgView.frame = CGRectMake(0, 0, CGRectGetWidth(keyWindow.frame), CGRectGetWidth(keyWindow.frame));
        imgView.center = keyWindow.center;
        bgView.backgroundColor = [UIColor colorWithWhite:0 alpha:1.0f];
    }];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                          action:@selector(hideImage:)];
    [bgView addGestureRecognizer:tap];
}

- (void)hideImage:(UITapGestureRecognizer *)gesture {
    
    UIView *bgView = gesture.view;
    UIImageView *imgView = (UIImageView *)bgView.subviews.firstObject;
    
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    
    [UIView animateWithDuration:0.2 animations:^{
        
        imgView.frame = [self.superview convertRect:self.frame toView:keyWindow];
        bgView.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
        
    } completion:^(BOOL finished) {
        
        NSLog(@"finished: %d", finished);
        
        [bgView removeFromSuperview];
    }];
}

@end
